#include "ParticleSystem.h"

namespace easy2d {


	Emitter::Emitter()
	{

	}

	Emitter::~Emitter()
	{

	}

	//////////////////////////////////////////////////////////////////////////

	Particle::Particle()
	{
		sprite = NULL;

		activeList = NULL;
		freeList = NULL;

		activeNum = 0;
		freeNum = 0;

	}

	Particle::~Particle()
	{

	}

	void Particle::update(uint elapsedTime)
	{

	}

	void Particle::render(IVideo* video)
	{
		if (sprite == NULL) {
			Image img;
			img.load("./assets/particles/fire.png");
			ITexture* tex = video->createTexture();
			tex->initialize(img);
			sprite = video->createSprite();
			sprite->initialize(tex->width(), tex->height(), NULL);
			sprite->texture(tex);

			addParticleNode();
		}

		stParticleNode* pParNode = activeList;
		while (pParNode) {
			RenderParam param;
			param.blend = BlendAdd;
			param.setColor(0xFFFFFFFF);
			param.px = 150;
			param.py = 150;


			
			video->drawSprite(sprite, 0, &param);

			pParNode = pParNode->next;
		}
	}

	void Particle::addParticleNode()
	{
		if ( isFull() )
			return;

		stParticleNode* pNewNode = new stParticleNode;
		if (activeList == NULL) activeList = pNewNode;
		else activeList->next = pNewNode;
		activeNum++;
	}

	bool Particle::isFull()
	{
		return activeNum == number;
	}

	//////////////////////////////////////////////////////////////////////////

	ParticleEffect::ParticleEffect()
	{
		Particle* par = new Particle;
		mParticleList.push_back(par);
	}

	ParticleEffect::~ParticleEffect()
	{
		while (!mParticleList.empty()) {
			delete mParticleList[mParticleList.size()-1];
			mParticleList.pop_back();
		}
	}

	void ParticleEffect::update(uint elapsedTime)
	{
		for (size_t i=0; i<mParticleList.size(); i++) {
			mParticleList[i]->update(elapsedTime);
		}
	}

	void ParticleEffect::render(IVideo* video)
	{
		for (size_t i=0; i<mParticleList.size(); i++) {
			mParticleList[i]->render(video);
		}
	}


	//////////////////////////////////////////////////////////////////////////

	ParticleSystem::ParticleSystem(IVideo* video)
	{
		mVideo = video;

		// Test
		createParticleEffect(NULL);
	}

	ParticleSystem::~ParticleSystem()
	{
		while (!mParList.empty()) {
			delete mParList[mParList.size()-1];
			mParList.pop_back();
		}
	}

	ParticleEffect* ParticleSystem::createParticleEffect(const char* filename)
	{
		ParticleEffect* parEffect = new ParticleEffect();
		mParList.push_back(parEffect);
		return parEffect;
	}

	void ParticleSystem::destroyParticleEffect(ParticleEffect*& parEffect)
	{
		delete parEffect;
		parEffect = NULL;
	}


	void ParticleSystem::update(uint elapsedTime)
	{
		for (size_t i=0; i<mParList.size(); i++) {
			mParList[i]->update(elapsedTime);
		}
	}

	void ParticleSystem::render()
	{
		for (size_t i=0; i<mParList.size(); i++) {
			mParList[i]->render(mVideo);
		}
	}

}	// namespace


